package com.lbd.gulimall.cart.interceptor;

import com.lbd.common.constrant.CommonAuthConstrant;
import com.lbd.common.to.MemberEntity;
import com.lbd.gulimall.cart.constrant.CartConstrant;
import com.lbd.gulimall.cart.to.OnlineUserTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author: linbd
 * @Description:
 * @Date: 2023/3/23 22:13
 */
@Slf4j
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<OnlineUserTO> onlineUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        OnlineUserTO user = new OnlineUserTO();
        MemberEntity member = (MemberEntity) request.getSession().getAttribute(CommonAuthConstrant.LOGIN_USER);
        if (member != null) {
            log.info("用户已登录...");
            //登录
            user.setUserId(String.valueOf(member.getId()));
        } else {
            //未登录
            log.info("用户未登录...");
        }
        //判断cookie是否有临时用户。登录状态下也把临时用户查出来（合并购物车）
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (CartConstrant.TEMP_USER.equals(name)) {
                    log.info("已经有临时用户...");
                    //已创建临时用户
                    String value = cookie.getValue();
                    user.setUserKey(value);
                }
            }
        }
        //cookie中如果存在就不再分配了
        if (StringUtils.isEmpty(user.getUserKey())) {
            log.info("未创建临时用户。添加临时用户...");
            String uuid = UUID.randomUUID().toString().substring(0, 10);
            user.setUserKey(uuid);
            user.setIsNew(true);
        }
        onlineUser.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        OnlineUserTO user = onlineUser.get();
        //未登录状态没有临时用户，需要创建。登录状态也可以创建一个临时用户不影响(判断是否是新创建的user-key，是的话设置过期时间，其余情况不设置)
        if (user.getIsNew()) {
            log.info("添加临时用户到Cookie...");
            Cookie cookie = new Cookie(CartConstrant.TEMP_USER, user.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstrant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
